<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
include 'printer.php';

class Admin extends CI_Controller {

  public function __construct()
  {
    parent::__construct();
    
    $this->load->model('store_model');    
    $this->load->model('item_model');
    $this->load->model('gen_bill_model');
    $this->load->helper('url');
    $this->load->library('table');
    $this->load->helper('form');
  }

  public function Login()
  {  
    $data = array(
                   'admin_logged_in' => FALSE
               );
    $this->session->set_userdata($data);
    $this->load->library('form_validation');
    $this->form_validation->set_rules('username', 'Username', 'callback_UsernameCheck');
    $this->form_validation->set_rules('password', 'Password', 'callback_PasswordCheck');
      
    if ($this->form_validation->run() == FALSE)
    {
      $this->load->view('admin/login');
    }
    else
    {
      redirect('admin/storelist', 'location', 301);
    } 
  }

  public function UsernameCheck($username)
  {
    $data = array(
                   'admin_id'  => $username,
                   'admin_logged_in' => FALSE
               );
    $this->session->set_userdata($data);
    return TRUE;
  }

  public function PasswordCheck($str)
  {
    $username = $this->session->userdata('admin_id');
    if (!$this->store_model->CheckUserName($username))
    {
      $this->form_validation->set_message('PasswordCheck', '用户名不存在');
      return FALSE;
    }//如果用户名不存在
    else
    {
      if (!$this->store_model->CheckPassword($username,$str))
      {
        $this->form_validation->set_message('PasswordCheck', '密码不正确');
        return FALSE;
      }//如果密码不正确
      else
      {
          $data = array(
                     'admin_id'  => $username,
                     'admin_logged_in' => TRUE
                     );
          $this->session->set_userdata($data);
        return TRUE;
      }//用户名密码匹配，成功登陆
    }//如果用户名存在
  }

	public function index()
	{  
    // $this->storelist();
    $this->Login();
	}

  public function IsLogin()
  {
    $IsLogin = $this->session->userdata('admin_logged_in');
    if ($IsLogin)
      return true;
    else
    {
      redirect('admin/login');
      return false;
    }
  }

  public function history()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $store_id = $this->input->get('store_id', TRUE);
    $fromdate = $this->input->get('fromdate', TRUE);
    $todate   = $this->input->get('todate', TRUE);
    $max      = $this->input->get('max', TRUE);
    $page     = $this->input->get('page', TRUE);

    if ($store_id == null or $store_id == "")
      $store_id = -1;
    if ($fromdate == null or $fromdate == "") // example 20150501
      $fromdate =  "20140101";          // first day of this month 
    if ($todate == null or $todate == "")
      $todate = date("Ymd");
    if ($max == null or $max == "" or $max==0)
      $max = 100;
    $page = (int)$page;
    if ($page == null or $page == "")
      $page = 1;

    $data['totallist'] = $this->gen_bill_model->get_con_bills_nums($store_id, $fromdate, $todate, $max, $page);
    $data['bills'] = $this->gen_bill_model->get_con_bills($store_id, $fromdate, $todate, $max, $page);
    $data['maxpage'] = (int)(($this->gen_bill_model->get_con_bills_nums($store_id, $fromdate, $todate, $max, $page)-1)/$max+1);
    $data['stores'] = $this->store_model->get_stores();
    $data['totalprice'] = $this->gen_bill_model->get_con_bills_total_price($store_id, $fromdate, $todate, $max, $page);
    $data['totalprice'] = $data['totalprice']['total_price'];
    $data['showdetail'] = false;
    $data['title'] = '外卖订单情况';
    $data['store_id'] = $store_id;
    $data['fromdate'] = $fromdate;
    $data['todate'] = $todate;
    $data['max'] = $max;
    $data['page'] = $page;
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/billlist', $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function historydetail()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $store_id = $this->input->get('store_id', TRUE);
    $fromdate = $this->input->get('fromdate', TRUE);
    $todate   = $this->input->get('todate', TRUE);
    $max      = $this->input->get('max', TRUE);
    $page     = $this->input->get('page', TRUE);

    if ($store_id == null or $store_id == "")
      $store_id = -1;
    if ($fromdate == null or $fromdate == "") // example 20150501
      $fromdate =  date("20140101");          // first day of this month 
    if ($todate == null or $todate == "")
      $todate = date("Ymd");
    if ($max == null or $max == "" or $max==0)
      $max = 100;
    $page = (int)$page;
    if ($page == null or $page == "")
      $page = 1;

    $data['totallist'] = $this->gen_bill_model->get_con_bills_nums($store_id, $fromdate, $todate, $max, $page);
    $data['bills'] = $this->gen_bill_model->get_con_bills($store_id, $fromdate, $todate, $max, $page);
    $data['maxpage'] = (int)(($this->gen_bill_model->get_con_bills_nums($store_id, $fromdate, $todate, $max, $page)-1)/$max+1);
    $data['stores'] = $this->store_model->get_stores();
    $data['totalprice'] = $this->gen_bill_model->get_con_bills_total_price($store_id, $fromdate, $todate, $max, $page);
    $data['totalprice'] = $data['totalprice']['total_price'];
    $data['showdetail'] = true;
    $data['title'] = '外卖订单情况';
    $data['store_id'] = $store_id;
    $data['fromdate'] = $fromdate;
    $data['todate'] = $todate;
    $data['max'] = $max;
    $data['page'] = $page;
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/billlist', $data);
    $this->load->view("templates/admin/admin_footer");
  }

  /**************** item management ****************/

  /* table : item 
    `item_id` int(11) NOT NULL AUTO_INCREMENT,
    `item_name` varchar(128) NOT NULL,
    `item_type` varchar(128) NOT NULL,
    `item_price` varchar(128) NOT NULL,
    `item_note` varchar(256) DEFAULT NULL,
    `item_pic` varchar(256) NOT NULL,
    `store_id` int(11) NOT NULL,
    `item_state` int(11) NOT NULL,
  */

  public function itemlist()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $store_id = $this->input->get('store_id', TRUE);
    $data['store_id'] = $store_id;
    $data['title'] = '商品管理 商店ID:' . $store_id;
    $data['itemlist'] = $this->item_model->get_items($store_id);

    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/itemlist', $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function newitem()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $store_id = $this->input->get('store_id', TRUE);
    if ($store_id == "")
    {
      redirect('/admin/storelist', 'refresh');
    }
    //deal with pic & info post
    $data['store_id'] = $store_id;
    $data['title'] = "添加商品 商店ID:" . $store_id;
    $data['result'] = '';

    if($_POST)
    {
      // todo:处理并存储图片
      $config['upload_path'] = 'uploads/item_pic/';
      $config['allowed_types'] = 'gif|jpg|png';
      $config['encrypt_name']  = TRUE;
      
      $this->load->library('upload', $config);
     
      if ( ! $this->upload->do_upload('item_pic'))
      {
        $data['error'] = array('error' => $this->upload->display_errors());
      
        if( $this->input->post('show_pic') == 'show' )
        {
          $data['result'] = "因为选择了显示封面图片，提交时必须上传图片：" . $data['error']['error'];
        }
        else
        {
          $this->item_model->new_item("", $store_id);
          $data['result'] = '添加成功(不显示图片)';
        }
      } 
      else
      {
        $res = array('upload_data' => $this->upload->data());
        $this->item_model->new_item($config['upload_path'] . $res['upload_data']['file_name'], $store_id);
        $data['result'] = '添加成功';
      }

    }    
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/newitem', $data);    
    $this->load->view("templates/admin/admin_footer");
  }

  public function updateitem()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $store_id = $this->input->get('store_id', TRUE);
    $item_id  = $this->input->get('item_id', TRUE);
    if ($store_id == "" or $item_id == "")
    {
      redirect('/admin/storelist', 'refresh');
    }

    $data['store_id'] = $store_id;
    $data['title'] = "更新商品 商店ID:" . $store_id;
    $data['result'] = '';

    // create new item
    if($_POST)
    {
      // delete old item
      $this->item_model->delete_item($item_id, $store_id);

      // todo:处理并存储图片
      $config['upload_path'] = 'uploads/item_pic/';
      $config['allowed_types'] = 'gif|jpg|png';
      $config['encrypt_name']  = TRUE;
      
      $this->load->library('upload', $config);
     
      if ( ! $this->upload->do_upload('item_pic'))
      {
        $data['error'] = array('error' => $this->upload->display_errors());       
        $tmp_item = $this->item_model->get_item($item_id);

        if ($tmp_item[0]["item_pic"] == "" and $this->input->post('show_pic') == 'show')
        {
            $data['result'] = "原图片不存在且选择显示图片，必需上传图片:" . $data['error']['error'];
        }
        else
        {
            $data['result'] = "除图片外其他信息更新成功:" . $data['error']['error'];
            $item_id = $this->item_model->new_item($tmp_item[0]["item_pic"], $store_id);
        }        
      } 
      else
      {
        $res = array('upload_data' => $this->upload->data());
        $item_id = $this->item_model->new_item($config['upload_path'] . $res['upload_data']['file_name'], $store_id);
      }
    }

    // return new item info
    $data['item'] = $this->item_model->get_item($item_id);
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/updateitem', $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function deleteitem()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $store_id = $this->input->get('store_id', TRUE);
    $item_id  = $this->input->get('item_id', TRUE);
    $this->item_model->delete_item($item_id, $store_id);
    redirect('/admin/itemlist?store_id='.$store_id, 'refresh');    
  }



  /**************** item management end ************/

  /**************** store management **************/
  public function storelist()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "店铺管理";
    $data['storelist'] = $this->store_model->get_stores();
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view("admin/storelist", $data);
    $this->load->view("templates/admin/admin_footer");
  }

  // 店铺销售图示
  public function storechart()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "店铺销售图示";
    $data['store'] = $this->store_model->get_store($this->input->get('store_id', TRUE));
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view("admin/storechart", $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function getdormdata()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
      $query = $this->gen_bill_model->get_dorm_data();
      $res = array(
            "total" => $this->gen_bill_model->get_dorm_data_count(),
            "items" => array()
        );

      foreach ($query as $row) 
      {
        array_push($res['items'], array(
          "dorm" => $row['dorm'],
          "count" => $row['count']
          ));
      }

      echo json_encode($res); 
  }

  //楼栋订单柱状图
  public function dormchart()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "楼栋订单柱状图";
    //$data['store'] = $this->store_model->get_store($this->input->get('store_id', TRUE));
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view("admin/dormchart", $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function timeTest($store_id)
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $time = time();
    $date = date('Y-m-d H:i:s', time());
    $hour = date('H', time());
    $minute = date('i', time());
    $second = date('s', time());
    $time2 = $time-$second-$minute*60-$hour*3600;
    $each = 24*3600;
    $timeArray = array();
    array_push($timeArray, $time2);
    for ($i = 1; $i<7; $i++)
      array_push($timeArray, $time2-$i*$each);

    //$count = [0,0,0,0,0,0,0];
    $count = array(0, 0, 0, 0, 0, 0, 0);
    $now = 0;

    $query = $this->gen_bill_model->get_shop_data($store_id);
    foreach ($query as $item) 
    {
      if ($item['time']>$timeArray[$now])
        $count[$now]++;
      else 
        while ($item['time']<=$timeArray[$now])
        {
          $now++;
          if ($now>=7) break;
        }
      if ($now>=7) break;
    }
    /*foreach ($count as $item) {
      echo "</br>";
      echo $item;
    }*/
    return $count;
  }

  public function getshopdata()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
      $store_id = $this->input->get('store_id', TRUE);
      $data = $this->timeTest($store_id);
      $res = array(
            //"total" => $this->gen_bill_model->get_dorm_data_count(),
            "items" => array()
        );

      foreach ($data as $row) 
      {
        array_push($res['items'], array(
          "count" => $row
          ));
      }

      echo json_encode($res); 
  }

  //单店铺一周营业额折线图
  public function shopchart()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "单店铺一周营业额折线图";
    //$data['store'] = $this->store_model->get_store($this->input->get('store_id', TRUE));
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view("admin/shopchart", $data);
    $this->load->view("templates/admin/admin_footer");
  }
  
  public function newstore()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    //deal with pic & info post
    $data['title'] = "添加店铺";
    $data['result'] = '';

    if($_POST)
    {
      // todo:处理并存储图片
      $config['upload_path'] = 'uploads/store_pic/';
      $config['allowed_types'] = 'gif|jpg|png';
      $config['encrypt_name']  = TRUE;
      
      $this->load->library('upload', $config);
     
      if ( ! $this->upload->do_upload('store_pic'))
      {
        $data['error'] = array('error' => $this->upload->display_errors());
        $data['result'] = $data['error']['error'];
      } 
      else
      {
       $res = array('upload_data' => $this->upload->data());
       $data['result'] = $this->store_model->new_store($config['upload_path'] . $res['upload_data']['file_name']);
      }

    }
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/newstore', $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function updatestore()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "更新店铺";
    $data['result'] = '';

    if($_POST)
    {
      // 处理并存储图片
      // 如果没有图片或符合要求的图片，忽略
      // 如果图片存储成功，返回正确的图片存储路径
      $config['upload_path'] = 'uploads/store_pic/';
      $config['allowed_types'] = 'gif|jpg|png';
      $config['encrypt_name']  = TRUE;
      
      $this->load->library('upload', $config);
     
      if ( ! $this->upload->do_upload('store_pic'))
      {
        $data['error'] = array('error' => $this->upload->display_errors());
        $data['result'] = "没有更新图片，因为：" . $data['error']['error'];
        $this->store_model->update_store("");
      } 
      else
      {
       $res = array('upload_data' => $this->upload->data());
       $data['result'] = $this->store_model->update_store($config['upload_path'] . $res['upload_data']['file_name']);
      }
    }

    $data['store'] = $this->store_model->get_store($this->input->get('store_id', TRUE));
    $this->load->view("templates/admin/admin_header", $data);
    $this->load->view('admin/updatestore', $data);
    $this->load->view("templates/admin/admin_footer");
  }

  public function printer()
  {
    $Printer = NetPrinterClass::getInstance(); 

    if (isset($Printer->params['id']) && isset($Printer->params['sta']))  // 返回打印结果
    {
      $sta = $this->input->get('sta',TRUE);
      $id = $this->input->get('id',TRUE);
      if ($sta == "0")//打印成功
      {
        $this->gen_bill_model->update_print_state($id);
      }
      else if ($sta == "1" || $sta == "3")//过热 or 缺纸卡纸
      {
        $IMEI = $this->input->get('usr', TRUE);
        $temp_store_id = $this->store_model->get_store_id($IMEI);
        $store_id = $temp_store_id['store_id'];

        $store_mail = $this->store_model->get_store_mail($store_id);
        $title = "";
        if ($sta == "1")
        {
          $title = "紧急情况:打印机故障-过热！！";
        }
        else 
        {
          $title = "紧急情况:打印机故障-缺纸卡纸！！";
        }
        $unprint_bills = $this->gen_bill_model->get_unprint_bills($store_id);

        $content = "下面是未打印的订单:\n\n\n";
        foreach ($unprint_bills as $bills) {
          $user_name = $bills['name'];
          $bill_id = $bills['bill_id'];
          $phone = $bills['phone'];
          $address = $bills['address'];
          $note = $bills['note'];
          $time = $bills['time'];
          $dorm = $bills['dorm'];
          if ($dorm == null or $dorm == 0)
            $dorm = "未填写";
          else
            $dorm = "宿舍 " . $dorm . " 号楼";
          $store_info = $this->store_model->get_store($store_id);
          $store_name = $store_info[0]['store_name'];
          $json = json_decode($bills['bill_json'],TRUE);
          $bill_total_price = $json['total_price'];
          $list = $json['list'];

          $content = $content."订购姓名：" . $user_name 
            ."\n订单编号：" . $bill_id
            ."\n联系电话：" . $phone
            ."\n送货地址：" . $address
            ."\n寝室楼栋：" . $dorm
            ."\n外卖备注：" . $note
            ."\n下单时间：" . date('Y-m-d H:i:s', $time)
            ."\n外卖店铺：" . $store_name
            ."\n外卖总价：" . $bill_total_price
            ."\n\n订单详情：";

          foreach ($list as $item):
            if ($item['item_account'] > 0)
              $content .= "\n" . $item['item_name'] . "\t\t" . $item['item_price'] . "\t\t" . $item['item_account'];
          endforeach;
          $divider = "\n----------------------------\n";
          $content = $content.$divider;
        }
        if (count($unprint_bills) > 0)
        {
          //echo mb_convert_encoding($content,"GBK", "UTF-8");  
          $this->send2mail($store_mail, $title, $content);
        }
      }
      else//未知错误
      {
      } 
    }
    else // 传输需要打印的内容
    {   
      $IMEI = $this->input->get('usr', TRUE);
      // echo $IMEI;
      if ($IMEI == "")//如果机器码为空
      {
        echo null;
      }
      else//机器码正常
      {
        // echo $IMEI;
        $temp_store_id = $this->store_model->get_store_id($IMEI);
        if ($temp_store_id == NULL)//如果该机器不属于任何一个商铺
        {
            $content = (string)$IMEI." not exist";
            return;
        }
        else//如果机器属于store_id商铺
        {
          $store_id = $temp_store_id['store_id'];
          $last_unprint_bill = $this->gen_bill_model->get_last_unprint_bill($store_id);
          if ($last_unprint_bill == null)//如果没有待打印订单
          {
            $bill_id = 0;
            $content = "store_id ".(string)$store_id." not exist";
          }
          else
          {
            $temp_content = $last_unprint_bill['bill_json'];
            //$content = "名称      数量%%";
            $json = json_decode($temp_content,TRUE);
            $content_list = $json["list"];

            //$content = $content_list;
            $name_length_const = 12;
            $number_length_const = 5;
            $price_length_const = 5;
            $total_price_length_const = 5;//常量定义
            $divider = "----------------------------%%";

            $content = "%30聚惠家外卖单%%";

            $store_info = $this->store_model->get_store($store_id);       
            $store_name = $store_info[0]['store_name'];
            $store_name = "%30".$store_name."%%";
            $content = $content.$store_name;//取店铺名称

            $character_time = "%00下单时间:";
            $time = $last_unprint_bill['time'];
            $time = date('Y-m-d H:i:s', $time);
            $content = $content.$character_time.$time."%%";//取下单时间

            $character_bill_id = "订单编号:";
            $bill_id = $last_unprint_bill['bill_id'];
            $content = $content.$character_bill_id.$bill_id."%%";//订单编号

            $content = $content.$divider;

            $character_name = "名称";
            $character_name = str_pad($character_name,$name_length_const+2,".");
            $character_number = "数量";
            $character_number = str_pad($character_number,$number_length_const+2,".",STR_PAD_LEFT);
            $character_price = "单价";
            $character_price = str_pad($character_price,$price_length_const+2,".",STR_PAD_LEFT);
            $character_total_price = "金额";
            $character_total_price = str_pad($character_total_price,$total_price_length_const+2,".",STR_PAD_LEFT);
            $content = $content.$character_name.$character_number.$character_price.$character_total_price."%%";

            foreach ($content_list as $cl) {
              if ( $cl["item_account"] > 0 == false)
                continue;

              $name = $cl["item_name"];//名称
              $name_length = strlen($name);
              if ($name_length*2/3 > $name_length_const)
              {
                $name = substr($name, 0,$name_length_const*3/2);
                $name_length = $name_length_const*3/2;
              }
              $name = str_pad($name,$name_length_const+$name_length/3,".");

              $account = $cl["item_account"];//数量
              $int_account = intval($account);//数量转int
              $account = str_pad($account,$number_length_const,".",STR_PAD_LEFT);

              $item_price = $cl["item_price"];//该物品单价
              $float_price = floatval($item_price);//单价转float
              $float_price = number_format($float_price,1,'.','');//格式化
              $item_price = str_pad($float_price,$price_length_const,".",STR_PAD_LEFT);

              $item_total_price = $float_price*$int_account;//计算得总价
              $item_total_price = number_format($item_total_price,1,'.','');//格式化
              $item_total_price = str_pad($item_total_price,$total_price_length_const,".",STR_PAD_LEFT);

              $temp = $name.$account.$item_price.$item_total_price."%%";
              $content = $content.$temp;
            }
            //$content = $temp_content;
            $content = $content.$divider;

            $character_all_total_price = "合计:";
            $total_price = $json['total_price'];
            $total_price = floatval($total_price);
            $total_price = number_format($total_price,1,'.','');
            $character_all_total_price = $character_all_total_price.(string)$total_price;
            $content = $content.$character_all_total_price."%%";//合计金额

            $character_user_name = "姓名:";
            $user_name = $last_unprint_bill['name'];
            $content = $content.$character_user_name.$user_name."%%";//顾客姓名

            $character_address = "地址:";
            $adress = $last_unprint_bill['address'];
            $content = $content.$character_address.$adress."%%";//地址

            $character_dorm = "楼栋:";
            $dorm = $last_unprint_bill['dorm'];
            if ($dorm == null or $dorm == 0)
              $dorm = "未填写";
            else
              $dorm = "宿舍 " . $dorm . " 号楼";
            $content = $content.$character_dorm.$dorm."%%";//地址

            $character_phone_number = "电话:";
            $phone_number = $last_unprint_bill['phone'];
            $content = $content.$character_phone_number.$phone_number."%%";//电话

            $character_note = "备注:";
            $note = $last_unprint_bill['note'];
            $content = $content.$character_note.$note."%%";//备注

            $logo = "Powered by 聚惠家";
            $erweima = "%50142Bhttp://weixin.qq.com/r/6UxrcznEHGRjrX0Q9xn7%%";
            $content = $content.$erweima.$logo;

            // $content = $content."%%%%%%%%%%%%%%%%".$content;
            $time = $last_unprint_bill['time'];

            //$bill_id = $last_unprint_bill['bill_id'];
            $toPrint = $Printer->setId($bill_id) // 设置ID
                    ->setTime($time) // 设置时间
                    ->setContent($content) // 设置content
                    // ->setSetting("101:6|105:0") // 设置打印机参数等数据，具体参考协议部分文件，建议非必要不要设置，也可以为空
                    ->display(); // 输出
            // echo mb_convert_encoding($bill_id,"GBK", "UTF-8");  
            echo mb_convert_encoding($toPrint,"GBK", "UTF-8"); 

          /* log vars */
            $printerUrl = 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
            $printerReturnContent = $toPrint; 
            $printer_store_id = $store_id;
            $printer_IMEI = $IMEI;
            $this->store_model->insertPrinterLog($printerUrl, $printerReturnContent, $printer_store_id,$IMEI);
            // $printerTime = $
          }
        } 
      }
    }
  }

  public function send2mail($mail, $title = "新订单", $content = "")
  {
    $config['protocol'] = 'smtp';
    $config['charset'] = 'utf-8';
    $config['wordwrap'] = TRUE;
    $config['smtp_host'] = 'smtp.163.com';
    $config['smtp_user'] = 'juhuijiainfo@163.com';
    $config['smtp_pass'] = 'juhuijiainfo123';

    $this->load->library('email');

    $this->email->initialize($config);


    $this->email->from('juhuijiainfo@163.com', '聚惠家邮件服务');
    $this->email->to('769904450@qq.com,'.'juhuijiainfo@163.com,'.$mail); //注意，部署之前需要将公邮打开

    $this->email->subject($title);
    $this->email->message($content); 

    $this->email->send();

  //echo $this->email->print_debugger();
  }

  public function deletestore()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "店铺删除";
    $this->store_model->delete_store();
    redirect('/admin/storelist', 'refresh');
  }

  public function backstore()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return;
    $data['title'] = "店铺恢复";
    $this->store_model->back_store();
    redirect('/admin/storelist', 'refresh');
  }

  public function closestore()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return; 
    $data['title'] = "店铺打烊";
    $this->store_model->close_store();
    redirect('/admin/storelist', 'refresh');
  }

  public function busystore()
  {
    $IsLogin = $this->IsLogin();
    if (!$IsLogin)
      return; 
    $data['title'] = "店铺忙碌";
    $this->store_model->busy_store();
    redirect('/admin/storelist', 'refresh');
  }

  public function check()
  {
    $interval_time_const = 60*15;//150s = 2.5min
    $unprint_bills = $this->gen_bill_model->get_unprint_all_bills();
    $num = 0;
    $content = "";
    foreach ($unprint_bills as $bills) 
    {
      $bill_time = $bills['time'];
      $bill_time = intval($bill_time);
      $now_time = time();
      $interval_time = $now_time-$bill_time;
      if ($interval_time > $interval_time_const)
      {       
        $num = $num + 1;
        $json = json_decode($bills['bill_json'],TRUE);
        $store_id = $json['store_id'];
        $user_name = $bills['name'];
        $bill_id = $bills['bill_id'];
        $this->gen_bill_model->update_send_email($bill_id);
        $phone = $bills['phone'];
        $address = $bills['address'];
        $note = $bills['note'];
        $time = $bills['time'];
        $store_info = $this->store_model->get_store($store_id);
        $store_name = $store_info[0]['store_name'];
        $bill_total_price = $json['total_price'];
        $list = $json['list'];

        $interval_time_min = round($interval_time/60);
        $interval_time_sec = $interval_time%60;
        $content = $content."已经超时:".(string)$interval_time_min."分".(string)$interval_time_sec."秒"
          ."\n订购姓名：" . $user_name 
          ."\n订单编号：" . $bill_id
          ."\n联系电话：" . $phone
          ."\n送货地址：" . $address
          ."\n外卖备注：" . $note
          ."\n下单时间：" . date('Y-m-d H:i:s', $time)
          ."\n外卖店铺：" . $store_name
          ."\n外卖总价：" . $bill_total_price
          ."\n\n订单详情：";

        foreach ($list as $item):
          $content .= "\n" . $item['item_name'] . "\t\t" . $item['item_price'] . "\t\t" . $item['item_account'];
        endforeach;
        $divider = "\n--------------------------------------------------------\n\n\n\n";
        $content = $content.$divider;
        //echo mb_convert_encoding($content,"GBK", "UTF-8");  

      }
    }
    if ($num == 0)
      echo "There is not exist a bill that is not printed!".(string)(time());
    else
    {
      $content = "请注意:以下订单已经下单还未被打印出来!"
              ."\n请及时联系店铺老板！"
              ."\n一共有".(string)$num."张订单"
              ."\n\n\n下面是未打印的订单:\n\n\n".$content;
      $store_mail = "tongshensi1992@163.com";
      $title = "紧急情况:超时订单!!!!";
      $this->send2mail($store_mail, $title, $content);
      echo mb_convert_encoding($content,"GBK", "UTF-8");
    }
  }

  /***************** store management end *****************/



  
}
